import { getToken, removeTokenAndUserInfo } from '@/utils/auth'
import axios from 'axios'
import router from '@/router'

const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },

  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const { code, msg, data } = response.data
    if (code === 1) {
      return data // 直接返回data
    } else {
      return Promise.reject(new Error(msg || '请求失败'))
    }
  },

  (error) => {
    const config = error.config
    const status = error.response?.status
    const msg = error.response?.data?.msg || '服务器错误'

    // 监控401状态码
    if (status === 401) {
      // 如果是 logout 接口，不提示
      if (config.url.includes('/user/logout')) {
        return Promise.resolve()
      }

      removeTokenAndUserInfo()
      router.push({ name: 'login' })
    }

    return Promise.reject(new Error(msg))
  },
)

export default request
